package com.gepengjun.springboot.jwt.controller;

import com.gepengjun.springboot.base.JsonResult.Result;
import com.gepengjun.springboot.base.JsonResult.ResultUtil;
import com.gepengjun.springboot.jwt.annotation.RequiredLogin;
import com.gepengjun.springboot.jwt.constant.JwtConstant;
import com.gepengjun.springboot.jwt.entity.Suser;
import com.gepengjun.springboot.jwt.service.SuserService;
import com.gepengjun.springboot.jwt.util.JwtUtil;
import com.gepengjun.springboot.jwt.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/jwt")
public class LoginController {

    @Autowired
    private SuserService suserService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map<String, String> map){
        String userName = map.get("loginName");
        String password = map.get("password");
        Suser suser = suserService.findByUserName(userName);
        if (suser == null) {
            return ResultUtil.error(-2,"用户名不存在");
        }else {
            String sPassword = suser.getPassword();
            if (password.equals(sPassword)){
                String token = JwtUtil.getToken(suser.getSerialNo(),suser.getUsername(),sPassword);
                redisUtil.set(JwtConstant.JWT_TOKEN+":"+suser.getSerialNo(),token,JwtConstant.JWT_TOKEN_REDIS_EXPIRE);
                response.setHeader("token",token);
                return ResultUtil.success("登录成功");
            }else {
                return ResultUtil.error(-3,"用户名密码不正确");
            }
        }
    }

    @GetMapping("/hello")
    @RequiredLogin
    public Result hello(){
        return ResultUtil.success();
    }
}
